package top.jsjkxyjs.blackbox.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.jsjkxyjs.blackbox.entity.Car;
import top.jsjkxyjs.blackbox.entity.Devbind;
import top.jsjkxyjs.blackbox.entity.User;
import top.jsjkxyjs.blackbox.mapper.CarMapper;
import top.jsjkxyjs.blackbox.mapper.DevBindMapper;
import top.jsjkxyjs.blackbox.mapper.IotMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class DevBindServiceImpl implements top.jsjkxyjs.blackbox.service.DevBindService {
	@Autowired
	DevBindMapper devBindMapper;
	@Autowired
	CarMapper carMapper;
	@Autowired
	IotMapper iotMapper;


	@Override
	public boolean addIotToUser(Devbind devbind, User user) {
		return devBindMapper.addIotToUser(devbind, user.getId()) > 0;
	}

	@Override
	public int countUsersAllIots(int userId) {
		return devBindMapper.countUsersAllIots(userId);
	}

	@Override
	public List getUsersAllIots(int userId) {
		List list = new ArrayList();
		List<Car> userAllCars = carMapper.getAllCarsByUserId(userId);
		if (userAllCars.size() == 0) {
			HashMap father = new HashMap<>();
			father.put("title", "[车辆] 未绑定车辆，请先绑定！");
			HashMap children = new HashMap<>();
			children.put("title", "[车辆] 此账户未绑定车辆！");
			children.put("disabled", "true");
			List childrenList = new ArrayList();
			childrenList.add(children);
			father.put("children", childrenList);
			list.add(father);
		}
		for (Car car : userAllCars) {
			HashMap<String, Object> father = new HashMap<>();
			List<Devbind> datas = devBindMapper.getUserAllDevByCarId(car.getId());
			List childrenList = new ArrayList();
			if (datas.size() > 0) {
				for (Devbind data : datas) {
					HashMap children = new HashMap<>();
					children.put("title", "[车辆]" + data.getPlace());
					children.put("href", "/user/iot/" + data.getDevId());
					childrenList.add(children);
				}
			} else {
				HashMap children = new HashMap<>();
				children.put("title", "[设备] 此车辆未绑定设备！");
				children.put("disabled", "true");
				childrenList.add(children);
			}
			father.put("children", childrenList);
			father.put("title", "[设备] " + car.getLicensePlate());
			list.add(father);
		}
		return list;
	}

	@Override
	public int countUsersAllIotsDatas(int userId) {
		List<Devbind> userDevs = devBindMapper.getUserDevs(userId);
		int sum = 0;
		for (Devbind userDev : userDevs) {
			sum += iotMapper.countUserIotData(userDev.getDevId());
		}
		return sum;
	}

	@Override
	public Devbind getUserByIot(int devId) {
		Devbind devUser = devBindMapper.getUserByIot(devId);
		return devUser;
	}

	@Override
	public int getAllIots() {

		List<Devbind> devBindMappers = devBindMapper.selectList(null);
		return devBindMappers.size();
	}
}
